<template>
  <view class="friends-container">
    <!-- 轻提示：WS重连中 -->
    <view v-if="reconnecting" style="background:#fffbe6;color:#8c6d1f;padding:12rpx 20rpx;font-size:22rpx;border-bottom:1rpx solid #f0e6cc;display:flex;align-items:center;gap:12rpx;">
      <text>🔄</text>
      <text>实时服务连接中，部分功能暂不可用...</text>
    </view>
    
    <!-- 轻提示：达到最大重连次数 -->
    <view v-if="maxAttemptsReached" style="background:#fff2f0;color:#d4380d;padding:12rpx 20rpx;font-size:22rpx;border-bottom:1rpx solid #ffccc7;display:flex;align-items:center;justify-content:space-between;">
      <view style="display:flex;align-items:center;gap:12rpx;">
        <text>⚠️</text>
        <text>连接失败次数过多，请手动重试</text>
      </view>
      <button @click="manualRetryConnection" style="background:#ff4d4f;color:white;border:none;border-radius:4rpx;padding:8rpx 16rpx;font-size:20rpx;">重试</button>
    </view>
    <!-- 在线状态：显示好友列表 -->
    <view v-if="isServerOnline">
      <!-- 搜索栏 -->
      <view class="search-section">
        <view class="search-box">
          <text class="search-icon">🔍</text>
          <input 
            class="search-input" 
            placeholder="搜索好友..." 
            v-model="searchKeyword"
            @input="handleSearch"
          />
        </view>
      </view>
      
      <!-- 功能按钮 -->
      <view class="action-buttons">
        <view class="action-btn" @click="navigateToAdd">
          <text class="action-icon">➕</text>
          <text class="action-text">添加好友</text>
        </view>
        <view class="action-btn" @click="navigateToRequests">
          <text class="action-icon">📨</text>
          <text class="action-text">好友请求</text>
          <view v-if="pendingRequestsCount > 0" class="badge">{{ pendingRequestsCount }}</view>
        </view>
        <view class="action-btn" @click="refreshFriends" :class="{ 'loading': isLoading }">
          <text class="action-icon">{{ isLoading ? '⏳' : '🔄' }}</text>
          <text class="action-text">{{ isLoading ? '刷新中...' : '刷新列表' }}</text>
        </view>
        <view class="action-btn" @click="navigateToChatList">
          <text class="action-icon">💬</text>
          <text class="action-text">聊天记录</text>
        </view>
      </view>
      
      <!-- 好友统计 -->
      <view class="stats-section">
        <view class="stat-item">
          <text class="stat-number">{{ totalFriends }}</text>
          <text class="stat-label">总好友</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ onlineFriends }}</text>
          <text class="stat-label">在线好友</text>
        </view>
        <view class="stat-item">
          <text class="stat-number">{{ recentFriends }}</text>
          <text class="stat-label">最近联系</text>
        </view>
      </view>
      
      <!-- 好友列表 -->
      <view class="friends-list">
        <view class="section-title">
          <text class="title-text">我的好友</text>
        </view>
        
        <!-- 空状态 -->
        <view v-if="filteredFriends.length === 0" class="empty-state">
          <text class="empty-icon">👥</text>
          <text class="empty-title">暂无好友</text>
          <text class="empty-desc">快去添加一些好友吧！</text>
          <button class="empty-action-btn" @click="navigateToAdd">
            <text class="btn-text">添加好友</text>
          </button>
        </view>
        
        <view 
          v-for="friend in filteredFriends" 
          :key="friend.id"
          class="friend-item"
          @click="openChat(friend)"
        >
          <view class="friend-avatar">
            <image 
              v-if="friend.avatar" 
              :src="friend.avatar" 
              class="avatar-image"
              mode="aspectFill"
            />
            <text v-else class="avatar-text">{{ friend.name.charAt(0) }}</text>
            <view class="presence-indicator" :class="friend.isOnline ? 'online' : 'offline'"></view>
          </view>
          
          <view class="friend-info">
            <view class="friend-header">
              <text class="friend-name">{{ friend.remark || friend.name }}</text>
              <text class="last-seen">{{ formatLastSeen(friend.lastSeen) }}</text>
            </view>
            <text class="friend-status" :class="friend.isOnline ? 'online' : 'offline'">{{ friend.isOnline ? '在线' : '离线' }}</text>
            <view v-if="friend.lastMessage" class="last-message">
              <text class="message-preview">{{ friend.lastMessage }}</text>
              <text class="message-time">{{ formatTime(friend.lastMessageTime) }}</text>
            </view>
            <view v-else class="last-message">
              <text class="message-preview">{{ friend.email }}</text>
              <text class="message-time">{{ formatTime(friend.lastMessageTime) }}</text>
            </view>
          </view>
          
          <view class="friend-actions">
            <button 
              class="action-btn-small" 
              @click.stop="openChat(friend)"
              title="开始聊天"
            >
              💬
            </button>
            <button 
              class="action-btn-small" 
              @click.stop="showFriendOptions(friend)"
              title="更多选项"
            >
              ⋯
            </button>
          </view>
        </view>
      </view>
      
      
    </view>
    
    <!-- 离线状态：显示离线提示页面 -->
    <view v-else class="offline-page">
      <view class="offline-content">
        <text class="offline-icon">📡</text>
        <text class="offline-title">服务器离线</text>
        <text class="offline-message">好友功能需要服务器在线才能使用</text>
        <text class="offline-hint">请检查网络连接后重试</text>
        <button class="retry-btn" @click="retryConnection">重试连接</button>
      </view>
    </view>

    <!-- 好友选项弹窗 -->
    <view v-if="showFriendOptionsModal" class="modal-overlay" @click="closeFriendOptions">
      <view class="modal-container" @click.stop>
        <view class="modal-header">
          <text class="modal-title">好友选项</text>
          <button class="close-btn" @click="closeFriendOptions">✕</button>
        </view>
        <view class="modal-content">
          <view class="option-item" @click="startChat">
            <text class="option-icon">💬</text>
            <text class="option-text">开始聊天</text>
          </view>
          <view class="option-item" @click="viewProfile">
            <text class="option-icon">👤</text>
            <text class="option-text">查看资料</text>
          </view>

          <view class="option-item danger" @click="removeFriend">
            <text class="option-icon">🗑️</text>
            <text class="option-text">删除好友</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import apiService from '@/utils/api-service.js'
import chatService from '@/utils/websocket-chat-service.js'
import appStateManager from '@/utils/app-state-manager.js'

export default {
  data() {
    return {
      isServerOnline: false, // 初始false，但onLoad会更新
      searchKeyword: '',
      friends: [], // 初始化为空数组，从服务器或本地存储加载
      pendingRequestsCount: 0,
      unreadNotifications: 0,
      showFriendOptionsModal: false,
      selectedFriend: null,
      isLoading: false,
      // 双信号+宽限
      healthOk: false,
      wsConnected: false,
      offlineGraceTimer: null,
      reconnecting: false,
      maxAttemptsReached: false
    }
  },
  
  computed: {
    filteredFriends() {
      if (!this.searchKeyword) {
        return this.friends.sort((a, b) => {
          // 在线好友优先，然后按最后消息时间排序
          if (a.isOnline && !b.isOnline) return -1
          if (!a.isOnline && b.isOnline) return 1
          return new Date(b.lastMessageTime) - new Date(a.lastMessageTime)
        })
      }
      
      const keyword = this.searchKeyword.toLowerCase()
      return this.friends.filter(friend => 
        friend.name.toLowerCase().includes(keyword) ||
        friend.status.toLowerCase().includes(keyword)
      )
    },
    
    totalFriends() {
      return this.friends.length
    },
    
    onlineFriends() {
      return this.friends.filter(friend => friend.isOnline).length
    },
    
    recentFriends() {
      const oneDayAgo = new Date(Date.now() - 24 * 60 * 60 * 1000)
      return this.friends.filter(friend => 
        new Date(friend.lastMessageTime) > oneDayAgo
      ).length
    }
  },
  
  onLoad() {
    console.log('好友列表页面加载')
    
    // 从状态管理器获取当前服务器状态
    const serverState = appStateManager.getState('server')
    this.isServerOnline = serverState.isOnline
    this.updateServerStatusDisplay()
    
    // 订阅服务器状态变化
    appStateManager.subscribe('server', (serverState) => {
      console.log('服务器状态变化:', serverState)
      this.isServerOnline = serverState.isOnline
      this.updateServerStatusDisplay()
      
      // 如果服务器上线，重新加载好友列表
      if (serverState.isOnline) {
        this.loadFriends()
      }
    })
    
    // 先从本地加载好友列表和缓存的在线状态，实现快速显示
    this.loadFriendsFromLocal()
    
    // 初始化WebSocket以接收在线状态更新
    this.initWsForOnline()
    
    // 然后再从服务器加载最新数据
    if (this.isServerOnline) {
      setTimeout(() => {
        this.loadFriendsFromServer().catch(error => {
          console.error('从服务器加载好友列表失败:', error)
        })
      }, 500)
    }
  },
  
  onUnload() {
    // 清理资源
    this.cleanup()
  },
  
  onShow() {
    // 页面显示时检查服务器状态
    const serverState = appStateManager.getState('server')
    this.isServerOnline = serverState.isOnline
    
    // 刷新服务器状态和好友列表
    appStateManager.refreshServerStatus().then(isOnline => {
      if (isOnline) {
        this.loadFriends()
      }
    })
    
    // 页面显示时主动请求在线状态更新
    if (chatService.isConnected) {
      this.refreshOnlineStatus()
    }
  },
  
  // 每次页面重新获得焦点时刷新在线状态
  onTabItemTap() {
    if (chatService.isConnected) {
      this.refreshOnlineStatus()
    }
  },
 
  // 不在页面隐藏/卸载时断开WS连接，由 App.vue 统一管理断连时机
  // onHide() {},
  // onUnload() {},

  onPullDownRefresh() {
    this.loadFriends().then(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    async initWsForOnline() {
      try {
        // 如果未初始化，则初始化并只订阅在线事件
        if (!chatService.isConnected) {
          console.log('开始初始化WebSocket聊天服务...')
          try {
            await chatService.init()
            console.log('WebSocket聊天服务初始化成功')
          } catch (error) {
            console.error('WebSocket聊天服务初始化失败:', error)
            // 显示错误提示，但不阻止后续代码执行
            uni.showToast({
              title: '在线状态服务连接失败',
              icon: 'none',
              duration: 2000
            })
          }
        }
        
        // 注册WebSocket连接状态变化监听器
        chatService.onStatusChange((info) => {
          console.log('[FriendsList] 收到statusChange', info)
          const st = info?.status
          if (st === 'connected') {
            this.wsConnected = true
            this.reconnecting = false
            this.setOnlineImmediate()
            this.loadFriendsFromServer().catch(() => {})
          } else if (st === 'disconnected' || st === 'error') {
            this.wsConnected = false
            this.reconnecting = false
            this.scheduleOfflineIfNeeded()
            
            // 连接断开时，将所有好友标记为离线
            this.markAllFriendsOffline()
          } else if (st === 'reconnecting') {
            this.reconnecting = true
            this.maxAttemptsReached = false
          } else if (st === 'max_attempts_reached') {
            this.reconnecting = false
            this.maxAttemptsReached = true
          }
        })
        
        // 注册在线状态变化监听器
        chatService.onOnlineStatusChange((statusInfo) => {
          console.log('[FriendsList] 收到在线状态变化', statusInfo)
          this.updateFriendsOnlineStatus(statusInfo.online)
        })
        
        // 如果WebSocket已连接，立即获取在线用户并更新状态
        if (chatService.isConnected) {
          const onlineUsers = chatService.getOnlineUsers()
          this.updateFriendsOnlineStatus(onlineUsers)
        }
      } catch (e) {
        console.error('初始化WS在线状态订阅失败:', e)
        uni.showToast({
          title: '在线状态服务初始化失败',
          icon: 'none',
          duration: 2000
        })
      }
    },
    
    // 更新好友在线状态
    updateFriendsOnlineStatus(onlineUserIds) {
      if (!Array.isArray(onlineUserIds)) return
      
      console.log('[FriendsList] 更新好友在线状态，在线用户:', onlineUserIds)
      
      // 将所有好友的在线状态更新为最新状态
      this.friends = this.friends.map(friend => {
        const friendId = Number(friend.id)
        const isOnline = onlineUserIds.includes(friendId)
        console.log(`[FriendsList] 好友 ${friend.name}(ID:${friendId}) 在线状态: ${isOnline}`)
        return { ...friend, isOnline }
      })
      
      // 保存更新后的好友列表
      this.saveFriends()
    },
    
    // 将所有好友标记为离线
    markAllFriendsOffline() {
      this.friends = this.friends.map(friend => ({ ...friend, isOnline: false }))
      this.saveFriends()
    },
    
    // 更新服务器状态显示
    updateServerStatusDisplay() {
      const status = appStateManager.getState("server")
      this.serverStatus = status.isOnline ? 'online' : 'offline'
      this.statusText = status.isOnline ? '服务器连接正常' : '服务器连接异常'
    },
    
    // 健康检查，仅在进入/重试时调用
    setOnlineImmediate() {
      this.isServerOnline = true
      if (this.offlineGraceTimer) {
        clearTimeout(this.offlineGraceTimer)
        this.offlineGraceTimer = null
      }
    },
    scheduleOfflineIfNeeded() {
      // 若两个信号都为false，则在宽限后才离线
      if (this.wsConnected || this.healthOk) return
      if (this.offlineGraceTimer) return
      this.offlineGraceTimer = setTimeout(() => {
        if (!this.wsConnected && !this.healthOk) {
          this.isServerOnline = false
        }
        this.offlineGraceTimer = null
      }, 5000)
    },
    
    // 加载好友列表
    async loadFriends() {
      try {
        if (this.isServerOnline) {
          // 在线模式：从服务器获取好友列表
          await this.loadFriendsFromServer()
        } else {
          // 离线模式：从本地存储加载
          this.loadFriendsFromLocal()
        }
      } catch (error) {
        console.error('加载好友列表失败:', error)
        // 如果服务器请求失败，回退到本地数据
        this.loadFriendsFromLocal()
      }
    },

    // 手动刷新好友列表
    async refreshFriends() {
      if (this.isLoading) return
      
      this.isLoading = true
      try {
        // 并行加载好友列表和刷新在线状态
        await Promise.all([
          this.loadFriends(),
          chatService.isConnected ? this.refreshOnlineStatus() : Promise.resolve()
        ])
        
        uni.showToast({
          title: '刷新成功',
          icon: 'success',
          duration: 1500
        })
      } catch (error) {
        console.error('刷新好友列表失败:', error)
        uni.showToast({
          title: '刷新失败',
          icon: 'error',
          duration: 1500
        })
      } finally {
        this.isLoading = false
      }
    },

    // 从服务器加载好友列表
    async loadFriendsFromServer() {
      try {
        const currentUser = uni.getStorageSync('currentUser')
        if (!currentUser) {
          console.log('未找到当前用户信息')
          return
        }

        const userData = JSON.parse(currentUser)
        const userId = await apiService.getUserId(userData)
        
        if (!userId) {
          console.log('无法获取用户ID')
          return
        }

        console.log('从服务器获取好友列表，用户ID:', userId)
        const response = await apiService.getFriends(userId)
        
        if (response.code === 'SUCCESS' && response.data) {
          // 转换后端数据格式为前端需要的格式
          this.friends = response.data.map(friendData => ({
            id: friendData.user.id,
            name: friendData.user.name,
            email: friendData.user.email,
            avatar: friendData.user.avatar || '',
            status: friendData.user.status || '离线',
            // 默认离线，稍后使用缓存在线列表立即刷新
            isOnline: false,
            lastSeen: friendData.user.last_login || new Date().toISOString(),
            lastMessage: '', // 暂时为空，后续可以从聊天记录获取
            lastMessageTime: friendData.added_at || new Date().toISOString(),
            remark: friendData.remark || friendData.user.name
          }))
          // 立即用缓存的在线列表刷新在线状态，避免闪烁
          this.updateFriendsOnlineStatusFromCache()
          
          // 保存到本地存储
          this.saveFriends()
          console.log('好友列表加载成功，数量:', this.friends.length)
        }
      } catch (error) {
        console.error('从服务器加载好友列表失败:', error)
        throw error
      }
    },

    // 从本地存储加载好友列表
    loadFriendsFromLocal() {
      try {
        const savedFriends = uni.getStorageSync('friends_list')
        if (savedFriends) {
          this.friends = JSON.parse(savedFriends)
          
          // 先使用缓存的在线状态（立即显示）
          this.updateFriendsOnlineStatusFromCache()
          
          // 然后再异步更新最新的在线状态
          this.updateOnlineStates()
          
          console.log('从本地加载好友列表，数量:', this.friends.length)
        }
      } catch (error) {
        console.error('从本地加载好友列表失败:', error)
      }
    },
    
    // 从缓存更新好友在线状态
    updateFriendsOnlineStatusFromCache() {
      try {
        // 获取缓存的在线用户列表
        const cachedUsers = chatService.getCachedOnlineUsers()
        
        if (cachedUsers.length > 0) {
          console.log('[FriendsList] 使用缓存的在线状态更新好友列表:', cachedUsers.length, '个用户')
          this.updateFriendsOnlineStatus(cachedUsers)
        }
      } catch (error) {
        console.error('从缓存更新好友在线状态失败:', error)
      }
    },
    
    // 保存好友列表
    saveFriends() {
      try {
        uni.setStorageSync('friends_list', JSON.stringify(this.friends))
      } catch (error) {
        console.error('保存好友列表失败:', error)
      }
    },
    
    // 搜索处理
    handleSearch() {
      // 搜索逻辑已在computed中处理
    },
    
    // 打开聊天
    openChat(friend) {
      uni.navigateTo({
        url: `/pages/chat/chat?userId=${friend.id}&userName=${friend.name}`
      })
    },
    
    // 跳转到聊天列表
    navigateToChatList() {
      uni.navigateTo({
        url: '/pages/chat/list'
      })
    },
    
    // 跳转到消息中心
    navigateToNotifications() {
      uni.navigateTo({
        url: '/pages/notifications/notifications'
      })
    },
    
    // 跳转到添加好友页面
    navigateToAdd() {
      uni.navigateTo({
        url: '/pages/friends/add/add'
      })
    },
    
    // 跳转到好友请求页面
    navigateToRequests() {
      uni.navigateTo({
        url: '/pages/friends/requests/requests'
      })
    },
    
    // 显示好友选项
    showFriendOptions(friend) {
      this.selectedFriend = friend
      this.showFriendOptionsModal = true
    },
    
    // 关闭好友选项
    closeFriendOptions() {
      this.showFriendOptionsModal = false
      this.selectedFriend = null
    },
    
    // 开始聊天
    startChat() {
      if (this.selectedFriend) {
        this.openChat(this.selectedFriend)
      }
      this.closeFriendOptions()
    },
    
    // 查看资料
    viewProfile() {
      if (this.selectedFriend) {
        uni.navigateTo({
          url: `/pages/friends/detail/detail?friendId=${this.selectedFriend.id}`
        })
      }
      this.closeFriendOptions()
    },
    

    
    // 删除好友
    async removeFriend() {
      if (!this.selectedFriend) return

      const currentUserStr = uni.getStorageSync('currentUser')
      if (!currentUserStr) {
        uni.showToast({ title: '用户未登录', icon: 'error' })
        return
      }
      const currentUser = JSON.parse(currentUserStr)
      const userId = currentUser.id
      const friendId = this.selectedFriend.id

      uni.showModal({
        title: '删除好友',
        content: `确定要删除好友 ${this.selectedFriend.name} 吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              const response = await apiService.deleteFriend(userId, friendId)
              if (response.code === 'SUCCESS') {
                await this.loadFriends()
                uni.showToast({ title: '好友已删除', icon: 'success' })
              } else {
                throw new Error('服务器返回失败')
              }
            } catch (error) {
              console.error('删除好友失败:', error)
              uni.showToast({ title: '删除失败', icon: 'error' })
            } finally {
              this.closeFriendOptions()
            }
          }
        }
      })
    },
    
    
    // 重试按钮：并行健康检查 + 促发WS重连
    retryConnection() {
      // 刷新服务器状态
      appStateManager.refreshServerStatus().then(isOnline => {
        this.isServerOnline = isOnline
        if (isOnline) {
          this.loadFriends()
        }
      })
      
      // 若未连接，则尝试重新初始化（内部会重连）
      if (!chatService.isConnected) {
        console.log('尝试重新初始化WebSocket连接...')
        chatService.init().catch(error => {
          console.error('重新初始化WebSocket连接失败:', error)
        })
      }
    },
    
    // 手动重试连接
    async manualRetryConnection() {
      try {
        console.log('手动重试WebSocket连接')
        this.maxAttemptsReached = false
        this.reconnecting = true
        
        // 调用WebSocket服务的手动重试方法
        await chatService.manualRetry()
        
        // 同时刷新服务器状态
        const isOnline = await appStateManager.refreshServerStatus()
        this.isServerOnline = isOnline
        
        if (isOnline) {
          this.loadFriends()
        }
        
        uni.showToast({
          title: '正在重试连接...',
          icon: 'loading',
          duration: 2000
        })
      } catch (error) {
        console.error('手动重试连接失败:', error)
        uni.showToast({
          title: '重试连接失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 格式化最后在线时间
    formatLastSeen(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚在线'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前在线`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前在线`
      } else {
        return date.toLocaleDateString()
      }
    },
    
    // 格式化时间
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) { // 1分钟内
        return '刚刚'
      } else if (diff < 3600000) { // 1小时内
        return `${Math.floor(diff / 60000)}分钟前`
      } else if (diff < 86400000) { // 1天内
        return `${Math.floor(diff / 3600000)}小时前`
      } else if (diff < 7 * 86400000) { // 7天内
        return `${Math.floor(diff / 86400000)}天前`
      } else {
        return date.toLocaleDateString()
      }
    },
    
    // 清理资源
    cleanup() {
      // 清理定时器
      if (this.offlineTimer) {
        clearTimeout(this.offlineTimer)
        this.offlineTimer = null
      }
      
      if (this.offlineGraceTimer) {
        clearTimeout(this.offlineGraceTimer)
        this.offlineGraceTimer = null
      }
      
      // 清理WebSocket连接
      try {
        // 移除状态监听器
        chatService.removeStatusCallback(() => {})
        // 移除在线状态监听器
        chatService.removeOnlineStatusCallback(() => {})
      } catch (e) {
        console.warn('清理WebSocket监听器失败:', e)
      }
    },
    // 刷新在线状态
    updateOnlineStates() {
      if (chatService.isConnected) {
        // 先获取当前缓存的在线用户
        const onlineUsers = chatService.getOnlineUsers()
        this.updateFriendsOnlineStatus(onlineUsers)
        
        // 然后主动请求最新的在线用户列表
        this.refreshOnlineStatus()
      } else {
        this.markAllFriendsOffline()
      }
    },
    
    // 主动刷新在线状态
    refreshOnlineStatus() {
      if (!chatService.isConnected) {
        console.log('[FriendsList] WebSocket未连接，无法刷新在线状态')
        return Promise.resolve()
      }
      
      console.log('[FriendsList] 主动请求刷新在线状态')
      
      // 发送请求
      chatService.requestOnlineUsers()
      
      // 返回一个Promise，等待在线状态更新
      return new Promise((resolve) => {
        // 设置一个临时的监听器来等待在线状态更新
        const tempCallback = (statusInfo) => {
          console.log('[FriendsList] 临时监听器收到在线状态更新:', statusInfo)
          this.updateFriendsOnlineStatus(statusInfo.online)
          
          // 移除临时监听器
          setTimeout(() => {
            chatService.removeOnlineStatusCallback(tempCallback)
          }, 100)
          
          resolve()
        }
        
        // 添加临时监听器
        chatService.onOnlineStatusChange(tempCallback)
        
        // 设置超时，避免永久等待
        setTimeout(() => {
          chatService.removeOnlineStatusCallback(tempCallback)
          console.log('[FriendsList] 刷新在线状态超时，使用缓存数据')
          const onlineUsers = chatService.getOnlineUsers()
          this.updateFriendsOnlineStatus(onlineUsers)
          resolve()
        }, 3000)
      })
    }
  }
}
</script>

<style scoped>
.friends-container {
  min-height: 100vh;
  background: #f5f5f5;
}

/* 搜索栏 */
.search-section {
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.search-box {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  border-radius: 20rpx;
  padding: 16rpx 20rpx;
}

.search-icon {
  font-size: 28rpx;
  color: #999;
  margin-right: 12rpx;
}

.search-input {
  flex: 1;
  font-size: 24rpx;
  color: #333;
  border: none;
  background: transparent;
}

/* 功能按钮 */
.action-buttons {
  display: flex;
  padding: 20rpx;
  gap: 16rpx;
  background: white;
  border-bottom: 1rpx solid #e0e0e0;
}

.action-btn {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  position: relative;
  transition: all 0.3s ease;
}

.action-btn:active {
  transform: scale(0.95);
  background: #e9ecef;
}

.action-icon {
  font-size: 32rpx;
  margin-bottom: 8rpx;
}

.action-text {
  font-size: 22rpx;
  color: #333;
  font-weight: 500;
}

.badge {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  background: #ff4757;
  color: white;
  border-radius: 12rpx;
  padding: 4rpx 8rpx;
  font-size: 18rpx;
  min-width: 24rpx;
  text-align: center;
}

/* 统计信息 */
.stats-section {
  display: flex;
  background: white;
  padding: 20rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.stat-item {
  flex: 1;
  text-align: center;
}

.stat-number {
  display: block;
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  margin-bottom: 4rpx;
}

.stat-label {
  font-size: 20rpx;
  color: #666;
}

/* 好友列表 */
.friends-list {
  background: white;
  margin-top: 20rpx;
}

.section-title {
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.title-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.friend-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.friend-item:active {
  background: #f8f9fa;
}

.friend-item:last-child {
  border-bottom: none;
}

.friend-avatar {
  position: relative;
  margin-right: 16rpx;
}

.avatar-image {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
}

.avatar-text {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-size: 32rpx;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
}

.presence-indicator {
  position: absolute;
  bottom: 4rpx;
  right: 4rpx;
  width: 18rpx;
  height: 18rpx;
  border-radius: 50%;
  border: 3rpx solid #fff;
  z-index: 2;
}
.presence-indicator.online  { background:#4CAF50; }
.presence-indicator.offline { background:#bfbfbf; }

.friend-status.online  { color:#4CAF50; }
.friend-status.offline { color:#999; }

.friend-info {
  flex: 1;
  min-width: 0;
}

.friend-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4rpx;
}

.friend-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.last-seen {
  font-size: 20rpx;
  color: #999;
  margin-left: 12rpx;
}

.friend-status {
  font-size: 22rpx;
  color: #4CAF50;
  margin-bottom: 4rpx;
}

.last-message {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.message-preview {
  font-size: 22rpx;
  color: #666;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.message-time {
  font-size: 18rpx;
  color: #999;
  margin-left: 12rpx;
}

.friend-actions {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
  margin-left: 12rpx;
}

.action-btn-small {
  background: #f8f9fa;
  border: 1rpx solid #e9ecef;
  border-radius: 6rpx;
  padding: 8rpx 12rpx;
  font-size: 20rpx;
  color: #666;
  min-width: 60rpx;
}

/* 空状态样式 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 24rpx;
  opacity: 0.6;
}

.empty-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 12rpx;
}

.empty-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.empty-action-btn {
  background: #007AFF;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
  font-weight: 500;
}

.empty-action-btn .btn-text {
  color: white;
}


/* 离线页面 */
.offline-page {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  padding: 40rpx;
}

.offline-content {
  text-align: center;
  color: #999;
}

.offline-icon {
  font-size: 120rpx;
  display: block;
  margin-bottom: 30rpx;
}

.offline-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #666;
  display: block;
  margin-bottom: 12rpx;
}

.offline-message {
  font-size: 24rpx;
  display: block;
  margin-bottom: 8rpx;
}

.offline-hint {
  font-size: 20rpx;
  opacity: 0.8;
  display: block;
  margin-bottom: 30rpx;
}

.retry-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 16rpx 32rpx;
  font-size: 24rpx;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  width: 90%;
  max-width: 500rpx;
  background: white;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #e0e0e0;
}

.modal-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background: #e74c3c;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 20rpx;
}

.modal-content {
  padding: 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.3s ease;
}

.option-item:last-child {
  border-bottom: none;
}

.option-item:active {
  background: #f8f9fa;
}

.option-item.danger {
  color: #ff4757;
}

.option-icon {
  font-size: 32rpx;
  margin-right: 20rpx;
}

.option-text {
  font-size: 28rpx;
  color: inherit;
}
</style>
